import math
import logging
from my_state import app_state
from tkinter import Canvas
import platform

logger = logging.getLogger("VoiceAssistant")

class FloatingMicWindow:
    def __init__(self, root):
        self.root = root
        root.title("Voice Assistant")
        root.attributes('-topmost', True)
        root.overrideredirect(True)  # 无边框
         # 获取屏幕尺寸
        screen_width = root.winfo_screenwidth()
        screen_height = root.winfo_screenheight()
        
        # 窗口大小
        window_width = 120
        window_height = 120
        
         # 计算右上角位置（屏幕宽度减去窗口宽度，向下偏移50像素）
        x_pos = screen_width - window_width - 10  # 向右偏移10像素
        y_pos = 50  # 向下偏移50像素
        
        # 设置窗口初始位置在右上角
        root.geometry(f'{window_width}x{window_height}+{x_pos}+{y_pos}')
        
        # 设置现代玻璃效果背景
        if platform.system() == 'Windows':
            root.configure(bg='#000001')  # 用于Windows透明效果的非常深色
            try:
                root.wm_attributes("-transparentcolor", "#000001")
            except:
                root.configure(bg='#13151a')  # 回退到深色背景
        else:
            root.configure(bg='#13151a')  # 深蓝黑色背景
            root.attributes('-alpha', 0.9)  # 非Windows系统使用半透明效果
        
        # 初始化拖动功能
        self.drag_data = {"x": 0, "y": 0, "dragging": False}
        root.bind("<ButtonPress-1>", self.on_drag_start)
        root.bind("<ButtonRelease-1>", self.on_drag_stop)
        root.bind("<B1-Motion>", self.on_drag_motion)
        
        # 创建画布 - 使用透明背景
        if platform.system() == 'Windows':
            canvas_bg = "#000001"  # 与窗口相同的透明色
        else:
            canvas_bg = "#13151a"  # 深蓝黑色背景
            
        self.canvas = Canvas(root, width=120, height=120, 
                             bg=canvas_bg, highlightthickness=0)
        self.canvas.pack()
        
        # 创建半透明圆形背景
        self.background_circle = self.canvas.create_oval(
            15, 15, 105, 105, 
            fill="#1e2230", outline="#4a5568", width=1.5
        )
        
        # 绘制精美的麦克风图标
        self.draw_beautiful_mic()
        
        # 创建状态指示灯
        self.indicator_id = self.canvas.create_oval(85, 20, 100, 35, fill="#ff5555", outline="#ffffff")
        
        # 连接状态指示器
        self.conn_indicator = self.canvas.create_text(25, 25, text="●", fill="#4a5568", 
                                                      font=("Arial", 10, "bold"))
        
        # 指令显示区域
        self.command_label = self.canvas.create_text(60, 95, text="", fill="#a0d2ff", 
                                                   font=("Segoe UI", 8), width=110)
        
        # 动画效果计数器
        self.animation_counter = 0
        
        # 初始化显示
        self.update_ui()
    
    def draw_beautiful_mic(self):
        """绘制精美的麦克风图标"""
        # 麦克风底座
        self.canvas.create_oval(40, 35, 80, 75, outline="#e2e8f0", width=2, fill="")
        
        # 内部装饰环
        self.canvas.create_oval(45, 40, 75, 70, outline="#94a3b8", fill="", width=1)
        
        # 中心点 - 蓝色能量核心
        self.mic_center = self.canvas.create_oval(55, 50, 65, 60, fill="#0088ff", outline="")
        
        # 支撑杆
        self.canvas.create_line(60, 75, 60, 85, fill="#e2e8f0", width=2)
        self.canvas.create_line(55, 85, 65, 85, fill="#e2e8f0", width=2)
        
        # 格栅线
        for i in range(0, 360, 90):
            rad = math.radians(i)
            x1 = 60 + 10 * math.cos(rad)
            y1 = 55 + 10 * math.sin(rad)
            x2 = 60 + 25 * math.cos(rad)
            y2 = 55 + 25 * math.sin(rad)
            self.canvas.create_line(x1, y1, x2, y2, fill="#94a3b8", width=1)
    
    def update_ui(self):
        """更新用户界面"""
        try:
            # 更新状态指示灯颜色
            if app_state.is_recording:
                # 动态呼吸效果
                intensity = int(100 + 155 * abs(math.sin(self.animation_counter / 4)))
                color = f"#{intensity:02x}{intensity:02x}ff"
                self.canvas.itemconfig(self.indicator_id, fill=color)
                
                # 脉动效果 - 录音时增大指示灯
                size_mult = 1 + 0.3 * abs(math.sin(self.animation_counter / 3))
                self.canvas.coords(self.indicator_id, 
                                  85 - 5*size_mult, 20 - 5*size_mult,
                                  100 + 5*size_mult, 35 + 5*size_mult)
            elif app_state.server_connected:
                self.canvas.itemconfig(self.indicator_id, fill="#00cc44")  # 绿色
                # 恢复到正常大小
                self.canvas.coords(self.indicator_id, 85, 20, 100, 35)
            else:
                self.canvas.itemconfig(self.indicator_id, fill="#ff5555")  # 红色
                self.canvas.coords(self.indicator_id, 85, 20, 100, 35)
            
            # 更新连接状态指示器
            if app_state.server_connected:
                self.canvas.itemconfig(self.conn_indicator, fill="#44ff77")
            else:
                self.canvas.itemconfig(self.conn_indicator, fill="#ff5566")
            
            # 更新中心点能量核心
            if app_state.is_recording:
                # 录音时脉冲效果
                core_size = 0.5 + abs(math.sin(self.animation_counter / 2))
                self.canvas.coords(self.mic_center, 
                                  60 - 5*core_size, 55 - 5*core_size,
                                  60 + 5*core_size, 55 + 5*core_size)
                self.canvas.itemconfig(self.mic_center, fill="#00aaff")
            else:
                self.canvas.coords(self.mic_center, 55, 50, 65, 60)
                self.canvas.itemconfig(self.mic_center, fill="#0088ff")
            
            # 更新指令显示
            if app_state.active_commands:
                command_text = app_state.active_commands[-1][:20]  # 截取前20字符
                self.canvas.itemconfig(self.command_label, text=command_text)
            
            # 更新透明度
            if app_state.wake_word_detected:
                self.canvas.itemconfig(self.background_circle, fill="#2e3a50")
            elif app_state.server_connected:
                self.canvas.itemconfig(self.background_circle, fill="#1e2230")
            else:
                self.canvas.itemconfig(self.background_circle, fill="#1a1c25")
                
        except Exception as e:
            logger.error(f"UI更新错误: {str(e)}")
        
        # 增加动画计数器
        self.animation_counter = (self.animation_counter + 1) % 100
        
        # 80ms后再次更新
        self.root.after(80, self.update_ui)
    
    def on_drag_start(self, event):
        """开始拖动"""
        self.drag_data["x"] = event.x
        self.drag_data["y"] = event.y
        self.drag_data["dragging"] = True
        
        # 拖动时突出显示背景
        self.canvas.itemconfig(self.background_circle, outline="#e2e8f0")
    
    def on_drag_stop(self, event):
        """停止拖动"""
        self.drag_data["dragging"] = False
        self.canvas.itemconfig(self.background_circle, outline="#4a5568")
    
    def on_drag_motion(self, event):
        """处理拖动"""
        if self.drag_data["dragging"]:
            x = self.root.winfo_x() - self.drag_data["x"] + event.x
            y = self.root.winfo_y() - self.drag_data["y"] + event.y
            self.root.geometry(f"+{x}+{y}")